package com.lingchou.cloud.process.client.listener.global;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lingchou.cloud.process.api.enums.CommentTypeEnum;
import com.lingchou.cloud.process.client.enums.BusinessKeyAndMQEnum;
import com.lingchou.cloud.process.client.util.ThreadLocalUtil;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局流程结束监听
 */
@Component
public class GlobalProcessCompleteListener extends AbstractFlowableEngineEventListener {
    protected Logger log = LoggerFactory.getLogger(this.getClass());
    private final AmqpTemplate amqpTemplate;
    protected final RuntimeService runtimeService;

    public GlobalProcessCompleteListener(AmqpTemplate amqpTemplate, RuntimeService runtimeService) {
        this.amqpTemplate = amqpTemplate;
        this.runtimeService = runtimeService;
    }

    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        //得到流程实例id
        ExecutionEntityImpl entity = (ExecutionEntityImpl) event.getEntity();
        String processInstanceId = entity.getProcessInstanceId();
        //业务KEY
        String businessKey = entity.getBusinessKey();
        String queueName = BusinessKeyAndMQEnum.matchQueue(businessKey);
        if (StrUtil.isEmpty(queueName)) {
            log.error("processCompleted 业务key匹配队列失败");
            return;
        }
        CommentTypeEnum commentTypeEnum = ThreadLocalUtil.popStatus();
        String processStatus = commentTypeEnum == null ? "" : commentTypeEnum.name();
        Map<String, String> map = new HashMap<>(16);
        map.put("messageType", "taskComplete");
        map.put("processInstanceId", processInstanceId);
        map.put("processStatus", processStatus);
        String msgBody = JSONUtil.toJsonStr(map);
        log.info("审批结束发送MQ，业务：{}，队列：{}，内容：{}", businessKey, queueName, msgBody);
        amqpTemplate.convertAndSend(DirectExchange.DEFAULT.getName(), queueName, msgBody);
    }

    @Override
    protected void taskCreated(FlowableEngineEntityEvent event){
        //得到流程实例id
        TaskEntityImpl entity = (TaskEntityImpl)event.getEntity();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(entity.getProcessInstanceId()).singleResult();
        String businessKey = processInstance.getBusinessKey();
        String queueName = BusinessKeyAndMQEnum.matchQueue(businessKey);
        if (StrUtil.isEmpty(queueName)) {
            log.error("taskCreated 业务key匹配队列失败");
            return;
        }
        Map<String, String> map = new HashMap<>(16);
        map.put("messageType", "taskNotify");
        map.put("userId", entity.getAssignee());
        map.put("processInstanceId", entity.getProcessInstanceId());
        map.put("startUserId", processInstance.getStartUserId());
        map.put("startTime", processInstance.getStartTime().toString());
        String msgBody = JSONUtil.toJsonStr(map);
        //审批通知
        log.info("审批通知，业务：{}，队列：{}，内容：{}", businessKey, queueName, msgBody);
        amqpTemplate.convertAndSend(DirectExchange.DEFAULT.getName(), queueName, JSONUtil.toJsonStr(map));
    }
}
